package JUC;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t异步回调无返回值~~");
        });
        voidCompletableFuture.get();

        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t有返回值");
            //int age = 10 / 0;
            return 1024;
        });

        System.out.println(integerCompletableFuture.whenComplete((r, e) -> {
            System.out.println(String.format("r: %s", r));
            System.out.println(String.format("e: %s", e));
        }).exceptionally(throwable -> {
            System.out.println("exception:" + throwable.getMessage());
            return 205;
        }).get());



        List<Integer> collect = new Random().ints(0,100).limit(20)
                .boxed().collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(collect.size(), 100));
        List<Integer> results = collect.stream().map(e -> CompletableFuture.supplyAsync(() -> {
            // 操作代码.....
           return e;

        }, executor)).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
        results.forEach(System.out::println);
    }
}
